package com.azkj.album.view.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.azkj.album.R;
import com.azkj.album.adapter.ClassPhotoSelectAdapter;
import com.azkj.album.dto.BackGroundListBean;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.dto.NewGalleryBean;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.utils.ImageUtils;
import com.azkj.album.utils.Utils;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.widgets.staggedrv.GridItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class NewPhotoSelectActivity extends BaseActivity {

    @BindView(R.id.tv_photo_class_layout)
    RelativeLayout mPhotoClassLayout;
    @BindView(R.id.rv_class_photo_layout)
    RecyclerView mRvPhotoClass;
    private ClassPhotoSelectAdapter classPhotoSelectAdapter;
    private List<NewGalleryBean> newGalleryBeans = new ArrayList<>();
    private ArrayList<String> imagesSelect = new ArrayList<>();
    private ArrayList<String> imagesFullSelect = new ArrayList<>();
    private ArrayList<String> imagesAll = new ArrayList<>();
    //新建图册选择的分类ID
    private Integer selectClassID;
    private Integer type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new_photo_select;
    }

    @Override
    public void initView() {
        Intent data = getIntent();
        newGalleryBeans = (List<NewGalleryBean>) data.getSerializableExtra("gallerList");
        type = data.getIntExtra("type",1);
        if (type == 2) {
            // 遍历newGalleryBeans，如果有选中，imagesSelect添加选中的图片
            for (int i = 0; i < newGalleryBeans.size(); i++) {
                if (newGalleryBeans.get(i).getSelect()) {
                    imagesSelect.add(newGalleryBeans.get(i).getFullUrl());
                    imagesFullSelect.add(newGalleryBeans.get(i).getFullUrl());
                }
            }
        }

        selectClassID = data.getIntExtra("classID", 0);
        if (newGalleryBeans != null) {
            for (int i = 0; i < newGalleryBeans.size(); i++) {
                if ("add".equals(newGalleryBeans.get(i).getImgPath())){
                    newGalleryBeans.remove(i);
                }
            }
        }
    }

    @Override
    public void initData() {
        classPhotoSelectAdapter = new ClassPhotoSelectAdapter(NewPhotoSelectActivity.this, R.layout.activity_add_photo_select);
        mRvPhotoClass.setLayoutManager(new GridLayoutManager(this, 4));
        mRvPhotoClass.addItemDecoration(new GridItemDecoration(this, 5));
        mRvPhotoClass.setAdapter(classPhotoSelectAdapter);
        classPhotoSelectAdapter.setType(type);
        classPhotoSelectAdapter.setNewData(newGalleryBeans);
        classPhotoSelectAdapter.setItemOnClickInterface((imageUrl, isSelected) -> {
            if (isSelected) {
                imagesSelect.add(imageUrl);
                imagesFullSelect.add(imageUrl);
            } else {
                imagesSelect.remove(imageUrl);
                imagesFullSelect.remove(imageUrl);
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_new_photo_select_next})
    public void onClick(View v) {
        if (Utils.isFastClick()) return;
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_new_photo_select_next:
                if (imagesSelect.size() == 0) {
                    ToastUtils.showCenterToast("请选择图片");
                    return;
                }
                if (type == 2){
                    jumpNext();
//                    saveNetWorkImg();
                }else {
                    jumpNext();
                }
                break;
        }
    }

    private void jumpNext(){
        for (int i = 0; i < newGalleryBeans.size(); i++) {
            if (!TextUtils.isEmpty(newGalleryBeans.get(i).getFullUrl())) {
                imagesAll.add(newGalleryBeans.get(i).getFullUrl());
            }else {
                imagesAll.add(newGalleryBeans.get(i).getImgPath());
            }
        }
        Intent next = new Intent(NewPhotoSelectActivity.this, NewPhotoBackgroundActivity.class);
        next.putExtra("imagesSelect", imagesSelect);
        next.putStringArrayListExtra("imagesAll", imagesAll);
        next.putExtra("selectClassID", selectClassID);
        // 携带type和detail
        next.putExtra("type", getIntent().getIntExtra("type", -1));
        next.putExtra("detail", getIntent().getSerializableExtra("detail"));
        if (type == 2){
            startActivityForResult(next, 1002);
        }else {
            startActivity(next);
        }
    }

    int count = 0;
    private void saveNetWorkImg(){
        count = 0;
        for (int i = 0; i < newGalleryBeans.size(); i++) {
            NewGalleryBean newGalleryBean = newGalleryBeans.get(i);
            if (!TextUtils.isEmpty(newGalleryBean.getFullUrl())){
                ImageUtils.downloadImgUrl(newGalleryBean.getFullUrl(), String.valueOf(i), i, new ImageUtils.HttpCallBackListener() {
                    @Override
                    public void onFinish(Bitmap bitmap) {

                    }

                    @Override
                    public void onFinish(String path, int position) {
                        runOnUiThread(()->{
                            newGalleryBeans.get(position).setImgPath(path);
                            count++;
                            if (count == newGalleryBeans.size()){
                                imagesSelect.clear();
                                imagesFullSelect.clear();
                                for (int i = 0; i < newGalleryBeans.size(); i++) {
                                    Log.d(TAG, "onFinish: " + newGalleryBeans.get(i).toString());
                                    if (newGalleryBeans.get(i).getSelect()) {
                                        imagesSelect.add(newGalleryBeans.get(i).getImgPath());
                                        imagesFullSelect.add(newGalleryBeans.get(i).getFullUrl());
                                    }
                                }
                                jumpNext();
                            }
                        });
                    }

                    @Override
                    public void onError() {

                    }
                });
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode){
            if (1002 == requestCode){
                ArrayList<String> imgSelect = (ArrayList<String>) data.getSerializableExtra("imagesSelect");
                int selectClassId = data.getIntExtra("selectClassID", 0);
                int bgId = data.getIntExtra("selectBackGroundID", 0);
                BackGroundListBean bgBean = (BackGroundListBean) data.getSerializableExtra("selectBackGroundBean");
                ArrayList<String> imagesAlls = (ArrayList<String>) data.getSerializableExtra("imagesAll");
                Intent intent = new Intent();
                intent.putStringArrayListExtra("imagesSelect", imgSelect);
                intent.putExtra("selectClassID", selectClassId);
                intent.putExtra("selectBackGroundID", bgId);
                intent.putExtra("selectBackGroundBean", bgBean);
                intent.putStringArrayListExtra("imagesAll", imagesAlls);
                intent.putStringArrayListExtra("imagesFullSelect", imagesFullSelect);
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        // 重新计算选中的图片
        imagesAll.clear();
    }

    @Override
    protected void initPresenter() {
    }

    public void onMessage(MessageEvent messageEvent) {
        super.onMessage(messageEvent);
        switch (messageEvent.getType()) {
            case MessageType.TYPE_ON_SAVE_SUCCESS:
                finish();
                break;
        }
    }
}
